package models

import (
	"errors"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

type User struct {
	ID         uint   `gorm:"primaryKey"`
	Username   string `gorm:"unique;size:100"`
	Password   string `gorm:"size:255"`
	RealName   string `gorm:"size:255"`
	Status     string `gorm:"size:255"`
	Role       string `gorm:"size:50"`
	CreateTime string `gorm:"size:255"`
	UpdateTime string `gorm:"size:255"`
}

type UserRole struct {
	RoleID   uint
	UserID   uint
	RoleName string `gorm:"-"` // [Todo]
}

func GetUserByUsername(username string) (*User, error) {
	var user User
	if err := DB.Where("username = ?", username).First(&user).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return &user, nil
}

func GetUserRole(userID uint) (*UserRole, error) {
	var ur UserRole
	sql := `
        SELECT r.id AS role_id, r.name AS role_name
        FROM roles r
        JOIN user_roles ur ON ur.role_id = r.id
        WHERE ur.user_id = ?
        LIMIT 1
    `
	err := DB.Raw(sql, userID).Scan(&ur).Error
	if err != nil {
		return nil, err
	}
	if ur.RoleID == 0 {
		return nil, errors.New("role not found for user")
	}
	return &ur, nil
}

func CheckPassword(hashedPwd, plainPwd string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hashedPwd), []byte(plainPwd))
	return err == nil
}
